import axios from 'axios'
import {ElMessage, ElMessageBox} from "element-plus"
import useUserStore from '@/stores/user.js'

const process = import.meta.env

const timeoutSeconds = 60000

const needReLoginCodes = [201, 202, 203]

const service = axios.create({
  baseURL: process.VITE_BASE_API, // url = base url + request url
  timeout: timeoutSeconds // request timeout
})

service.interceptors.request.use(
    config => {

      const userStore = useUserStore()
      if (userStore.getToken) {
        config.headers['token'] = userStore.getToken
      }
      return config
    },
    error => {
      // do something with request error
      // console.log(error) // for debug
      return Promise.reject(error)
    }
)

service.interceptors.response.use(
    /**
     * If you want to get http information such as headers or status
     * Please return  response => response
     */

    /**
     * Determine the request status by custom code
     * Here is just an example
     * You can also judge the status by HTTP Status Code
     */
    response => {
      if (response.status !== 200) {
        ElMessage.error({
          message: '系统繁忙，请稍后再试',
          duration: 5000
        })
        return Promise.reject(new Error(response.statusText || 'Error'))
      }
      const res = response.data
      // if the custom code is not 20000, it is judged as an error.
      if (res.code !== 200) {
        if (needReLoginCodes.indexOf(res.code) < 0) {
          ElMessage.error({
            message: res.message || 'Error',
            duration: 5000
          })
          return Promise.reject(new Error(res.message || 'Error'))
        } else {
          // to re-login
          ElMessageBox.confirm('您已退出登录或在其他设备登录，可以取消停留在此页面，或在此登录', '确认退出登录', {
            confirmButtonText: '重新登录',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            const userStore = useUserStore()
            // 退出登录操作
            userStore.logout()
            window.location.reload()
          }).catch(() => {})
          return null
        }
      } else {
        return res.data
      }
    },
    // 网络链接的
    error => {
      if (error.message === 'Network Error') {
        error.message = '网络连接失败'
      } else if (error.message === ('timeout of ' + timeoutSeconds + 'ms exceeded')) {
        error.message = '网络连接超时'
      }
      ElMessage.error({
        message: error.message,
        duration: 5000
      })
      return Promise.reject(error)
    }
)

export default service